//
//  RSDBRelation.m
//  Chord Viewer
//
//  Created by Johnnie Walker on 05/09/2008.
//  Copyright 2008 Random Sequence. All rights reserved.
//

#import "RSDBRecord.h"
#import "RSDBRelation.h"
#import "RSDBTable.h"

@implementation RSDBRelation
@synthesize type, localTable, foreignTable, refTable, owningTable, localKey, foreignKey;

- (void) dealloc
{
	self.localTable = nil;
	self.foreignTable = nil;
	self.refTable = nil;
	self.owningTable = nil;
	self.localKey = nil;
	self.foreignKey = nil;
	
	[super dealloc];
}


+ (id)relationWithType:(RSDBRecordRelationType)type options:(NSDictionary *)options
{
	return [[[RSDBRelation alloc] initWithType:type options:options] autorelease];		
}

- (id)initWithType:(RSDBRecordRelationType)type options:(NSDictionary *)options
{
	self = [super init];
	
	if ([options objectForKey:RSDBRelationLocalKey]) {
		[self setLocalKey:[options objectForKey:RSDBRelationLocalKey]];
	}

	if ([options objectForKey:RSDBRelationForeignKey]) {
		[self setForeignKey:[options objectForKey:RSDBRelationForeignKey]];
	}

	if ([options objectForKey:RSDBRelationLocalTableKey]) {
		[self setLocalTable:[options objectForKey:RSDBRelationLocalTableKey]];
	}

	if ([options objectForKey:RSDBRelationForeignTableKey]) {
		[self setForeignTable:[options objectForKey:RSDBRelationForeignTableKey]];
	}

	if ([options objectForKey:RSDBRelationRefTableKey]) {
		[self setRefTable:[options objectForKey:RSDBRelationRefTableKey]];
	}

	if ([options objectForKey:RSDBRelationOwningTableKey]) {
		[self setOwningTable:[options objectForKey:RSDBRelationOwningTableKey]];
	}
		
	return self;
}

- (NSString *)description
{
	return [NSString stringWithFormat:@"%@\n type: %i\n localTable: %@\n foreignTable: %@\n localKey: %@\n foreignKey: %@\n",[super description],type,localTable,foreignTable,localKey,foreignKey];
}

// one-to-many methods

- (RSDBRecord *)getOwnerForRecord:(RSDBRecord *)record
{
	if (nil == [record valueForProperty:localKey]) {
		return nil;
	}
	
	NSString *sql = [NSString stringWithFormat:@"SELECT * FROM <tablename> WHERE %@ = ? LIMIT 1",foreignKey];
#ifdef DEBUG_BUILD
	// NSLog(@"getOwnerForRecord: %@ (%@) table: %@",sql,[record valueForProperty:localKey],foreignTable);
#endif
	return [foreignTable findOneBySQL:sql arguments:[NSArray arrayWithObject:[record valueForProperty:localKey]]];	
}

- (NSArray *)getRecordsOwnedBy:(RSDBRecord *)record
{	
	NSString *sql = [NSString stringWithFormat:@"SELECT * FROM <tablename> WHERE %@ = ?",foreignKey];
//	if ([foreignTable hasColumn:@"sequence"]) {
//		sql = [sql stringByAppendingString:@" ORDER BY sequence ASC"];
//	}
#ifdef DEBUG_BUILD	
	// NSLog(@"getRecordsOwnedBy: %@ table: %@",sql,[foreignTable tableName]);
#endif	
	return [foreignTable findBySQL:sql,[record valueForProperty:localKey]];					
}

@end
